package longrise.phone.com.bjjt_henan.main;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.PaintDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.FrameworkManager;
import com.longrise.android.ILFMsgListener;
import com.longrise.android.ILSMsgListener;
import com.longrise.android.LFView;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.util.PrefUtils;
import com.longrise.bjjt.util.UiUtil;

import java.util.Date;

import longrise.phone.com.bjjt_henan.Constant.MsgConstant;
import longrise.phone.com.bjjt_henan.Constant.URLConstant;
import longrise.phone.com.bjjt_henan.MainActivity;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.ApiImpI;
import longrise.phone.com.bjjt_henan.Utils.CommontUtils;
import longrise.phone.com.bjjt_henan.Utils.DialogUtils;
import longrise.phone.com.bjjt_henan.Utils.PermissionHelper;
import longrise.phone.com.bjjt_henan.bindinginformation.BindCarView;
import longrise.phone.com.bjjt_henan.bindinginformation.BindDriveCardView;
import longrise.phone.com.bjjt_henan.bindinginformation.PersonalInfoView;
import longrise.phone.com.bjjt_henan.compensate.InsuranceReportView;
import longrise.phone.com.bjjt_henan.compensate.NewLossLoadPicView;
import longrise.phone.com.bjjt_henan.service.LocationService;
import longrise.phone.com.bjjt_henan.widget.PromptDialog;

/**
 * 主页面
 */
public class NewMainView extends LFView implements RadioGroup.OnCheckedChangeListener, ILSMsgListener,
        ILFMsgListener {

    private View mView;

    private Context mContext;

    private LinearLayout bodyLayout;

    private RadioGroup radioGroup;

    private NewKckpView kckpView;//快处快赔

    private PersonalInfoView myView;//我的

    private EntityBean bindBean;//是否绑定的返回参数

    protected boolean isExit = false;

    private int bindState = -1;//-1表示查询失败;0表示查询成功;1表示数据完整

    private String redes;//失败的提示

    private LFView curShowView;//当前显示的页面

    private CarDailyView carDailyView;//车生活

    private boolean isBack = false;

    public NewMainView(Context context) {
        super(context);
        this.mContext = context;
    }

    public void setBack(boolean back) {
        isBack = back;
    }

    @Override
    public View getView() {
        return mView;
    }

    @Override
    public FormParameter getFormParameter() {
        FormParameter fp = new FormParameter();
        fp.setShowtitle(false);
        return fp;
    }

    @Override
    public void init() {
        if (mContext == null) {
            return;
        }
        mView = LayoutInflater.from(mContext).inflate(R.layout.view_newmain, null);
        if (mView == null) {
            return;
        }
        bodyLayout = (LinearLayout) mView.findViewById(R.id.newmain_layout);
        radioGroup = (RadioGroup) mView.findViewById(R.id.newmain_rgroup);
        setRBtnSize();
        setListen(true);
        switchView(1);

        setMark();

        if (PermissionHelper.checkLocPermissions(mContext)) {
            startService();
        }
    }

    //设置导航项统一的图片宽高
    private void setRBtnSize() {
        Drawable kDrawable = ContextCompat.getDrawable(mContext, R.drawable.mainview_cardaily_bg);
        int width = kDrawable.getIntrinsicWidth();
        int height = kDrawable.getIntrinsicHeight();

        RadioButton cdRBtn = (RadioButton) mView.findViewById(R.id.newmain_rbtn_kckp);
        Drawable cdDrawable = ContextCompat.getDrawable(mContext, R.drawable.mainview_kckpbtn_bg);
        cdDrawable.setBounds(0, 0, width, height);
        cdRBtn.setCompoundDrawables(null, cdDrawable, null, null);

        RadioButton myRBtn = (RadioButton) mView.findViewById(R.id.newmain_rbtn_my);
        Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.mainview_personalbtn_bg);
        drawable.setBounds(0, 0, width, height);
        myRBtn.setCompoundDrawables(null, drawable, null, null);
    }

    //切换显示的页面
    private void switchView(int pos) {
        if (bodyLayout == null) {
            return;
        }
        if (pos == 1) {//快处快赔
            if (kckpView == null) {
                kckpView = new NewKckpView(mContext);
                kckpView.init();
            }
            kckpView.refresh();
            curShowView = kckpView;
        } else if (pos == 2) {
            if (myView == null) {
                myView = new PersonalInfoView(mContext, null);
                myView.init();
                myView.refresh();
            }
            curShowView = myView;
        } else if (pos == 3) {
            if (carDailyView == null) {
                carDailyView = new CarDailyView(mContext);
                carDailyView.init();
                carDailyView.refresh();
            }
            curShowView = carDailyView;
        }
        //添加到主页面中
        bodyLayout.removeAllViews();
        bodyLayout.addView(curShowView.getView(), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        //刷新数据
        refreshView();
    }

    private void setListen(boolean flag) {
        if (radioGroup != null) {
            radioGroup.setOnCheckedChangeListener(flag ? this : null);
        }
        if (flag) {
            addILSMsgListener(this);
            addILFMsgListener(this);
        } else {
            removeILSMsgListener(this);
            removeILFMsgListener(this);
        }
    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public void refresh() {

    }

    //首页显示指引蒙版图
    private void setMark() {
        boolean flag = PrefUtils.getBoolean(mContext, "isFirst", false);
        if (flag) {
            getBindData(true);
            return;
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                showGuidePop();
                PrefUtils.setBoolean(mContext, "isFirst", true);
            }
        }, 50);
    }

    private PopupWindow popupWindow;

    //显示蒙版效果
    private void showGuidePop() {
        final LinearLayout layout = new LinearLayout(mContext);
        layout.setOrientation(LinearLayout.VERTICAL);
        popupWindow = new PopupWindow(layout, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT, true);
        popupWindow.setBackgroundDrawable(new PaintDrawable());
        popupWindow.setFocusable(true);
        View parent = ((Activity) mContext).getWindow().getDecorView();
        popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);

        ImageView fView = new ImageView(mContext);
        fView.setScaleType(ImageView.ScaleType.FIT_XY);
        fView.setImageBitmap(CommontUtils.readBitmap(mContext, R.mipmap.popwindow_bg_1));
        fView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageView sView = new ImageView(mContext);
                sView.setScaleType(ImageView.ScaleType.FIT_XY);
                sView.setImageBitmap(CommontUtils.readBitmap(mContext, R.mipmap.popwindow_bg_2));
                sView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (null != popupWindow) {
                            popupWindow.dismiss();
                            popupWindow = null;
                        }
                        getBindData(true);
                    }
                });
                layout.removeAllViews();
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT);
                layout.addView(sView, params);
                params = null;
            }
        });
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        layout.addView(fView, params);
        params = null;
        popupWindow.update();
    }

    //判断是否显示年检提醒框
    private void checkInspect() {
        try {
            if (bindBean == null) {
                return;
            }
            EntityBean[] carBeans = bindBean.getBeans("car");
            if (carBeans == null) {//未绑定机动车
                return;
            }
            for (int i = 0; i < carBeans.length; i++) {
                String carno = carBeans[i].getString("carno");
                long days = PrefUtils.getLong(mContext, carno, -1);
                if (days > 0) {//设置了提醒
                    long curTime = new Date().getTime();
                    if (curTime >= days) {//到时间了
                        showInspectDialog(carno);
                        PrefUtils.setLong(mContext, carno, -1);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showInspectDialog(String carno) {
        final Dialog dialog = new Dialog(mContext, R.style.AlertDialogStyle);
        View view = View.inflate(mContext, R.layout.dialog_inspect_notification, null);
        TextView carnoTV = (TextView) view.findViewById(R.id.dialog_tv_carno);
        carnoTV.setText("您的爱车：" + carno);
        view.findViewById(R.id.dialog_btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setContentView(view);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics d = mContext.getResources().getDisplayMetrics(); // 获取屏幕宽、高用
        lp.width = (int) (d.widthPixels * 0.85);
        dialogWindow.setAttributes(lp);
        dialog.show();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.newmain_rbtn_kckp://快处快赔
                switchView(1);
                break;
            case R.id.newmain_rbtn_my://我的
                switchView(2);
                break;
            case R.id.newmain_rbtn_cardaily://车生活
                switchView(3);
                break;
            default:
                break;
        }
    }

    /**
     * 刷新当前显示界面的数据
     */
    private void refreshView() {
        if (null == curShowView) {
            return;
        }
        if (curShowView instanceof NewKckpView) {
            ((NewKckpView) curShowView).setView(this);
            ((NewKckpView) curShowView).setBindState(bindState);
            ((NewKckpView) curShowView).setBindBean(bindBean);
        } else if (curShowView instanceof PersonalInfoView) {
            ((PersonalInfoView) curShowView).setBindBean(bindBean);
        } else if (curShowView instanceof CarDailyView) {
            ((CarDailyView) curShowView).setBindState(bindState);
            ((CarDailyView) curShowView).setEntityBean(bindBean);
        }
    }

    /**
     * 查询绑定的车辆信息
     */
    private void getBindData(final boolean isToast) {
        try {
            BaseApplication application = ((MainActivity) mContext).getAppData();
            EntityBean baseBean = application.getLoginInfo().getBean("userinfo");
            String userId = baseBean.getString("id");
            String token = application.getToken();
            if (isToast) {
                DialogUtils.showDialog(mContext);
            }
            ApiImpI.getInstance(mContext.getApplicationContext()).bindState(userId, token,
                    new ApiImpI.RequestCallBack() {
                        @Override
                        public void onError(String error) {
                            DialogUtils.closeDialog();
                            if (null != kckpView) {
                                kckpView.finishRefresh();
                            }
                            if (!TextUtils.isEmpty(error)) {
                                UiUtil.showToast(mContext, error);
                            }
                        }

                        @Override
                        public void onSuccess(Object result) {
                            if (isBack) {
                                DialogUtils.closeDialog();
                            }
                            if (null != kckpView) {
                                kckpView.finishRefresh();
                            }
                            EntityBean bean = (EntityBean) result;
                            if (bean != null) {
                                bindState = 0;
                                bindBean = bean.getBean("data");
                                String restate = bean.getString("restate");
                                redes = bean.getString("redes");
                                if ("1".equals(restate)) {//用户已绑定驾驶证和行驶证信息
                                    bindState = 1;
                                }
                                if (isToast && !isBack) {
                                    checkInspect();
                                }
                                refreshView();
                                //保存车辆和驾驶证的数据
                                String carInfo = com.longrise.LEAP.Base.IO.JSONSerializer.getInstance().Serialize(bean);
                                PrefUtils.setString(mContext, "carinfo", carInfo);
                                LSMsgCall(102, "carinfo");

                                if (isToast && !isBack) {
                                    insReport();
                                }
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private PromptDialog dialog;

    public void showBindDialog() {
        if (null == dialog) {
            String title = mContext.getString(R.string.insurance_wait);
            dialog = new PromptDialog(mContext);
            dialog.setCanceledOnTouchOutside(false);
            dialog.setConfirm("立即绑定", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    if (bindBean == null) {//未绑定信息
                        LFView view = new BindDriveCardView(mContext, null);
                        FrameworkManager.getInstance().showNewForm(mContext, view);
                        return;
                    }
                    EntityBean cardBean = bindBean.getBean("use");
                    if (cardBean == null) {//未绑定驾驶证
                        LFView view = new BindDriveCardView(mContext, null);
                        FrameworkManager.getInstance().showNewForm(mContext, view);
                        return;
                    }
                    if (cardBean != null) {
                        String cardno = cardBean.getString("cardno");
                        String cardImg = cardBean.getString("drivernoimg");
                        String fileno = cardBean.getString("driverfileno");
                        if (TextUtils.isEmpty(cardno) || TextUtils.isEmpty(cardImg) || TextUtils.isEmpty(fileno)
                                || TextUtils.equals(fileno, "档案编号未填写")) {
                            //驾驶证信息有缺失
                            LFView view = new BindDriveCardView(mContext, cardBean);
                            FrameworkManager.getInstance().showNewForm(mContext, view);
                            return;
                        }
                    }
                    EntityBean[] carBeans = bindBean.getBeans("car");
                    if (carBeans == null) {//未绑定机动车
                        LFView view = new BindCarView(mContext, null);
                        FrameworkManager.getInstance().showNewForm(mContext, view);
                        return;
                    }
                    if (carBeans != null) {
                        EntityBean bean = carBeans[0];
                        //机动车信息有缺失
                        LFView view = new BindCarView(mContext, bean);
                        FrameworkManager.getInstance().showNewForm(mContext, view);
                        return;
                    }
                }
            });
            dialog.setCancel("返回", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog.setTitleNoIcon(title);
        }
        dialog.setInfo(redes);
        dialog.show();
    }

    //是否一键保险报案
    private void insReport() {
        BaseApplication application = ((MainActivity) mContext).getAppData();
        EntityBean baseBean = application.getLoginInfo().getBean("userinfo");
        String phone = baseBean.getString("mobilephone");
        String userId = application.getKckpName();
        String token = application.getToken();
        ApiImpI.getInstance(mContext.getApplicationContext()).insReport(phone, userId, token, new ApiImpI.RequestCallBack() {
            @Override
            public void onError(String error) {
                DialogUtils.closeDialog();
                if (!TextUtils.isEmpty(error)) {
                    UiUtil.showToast(mContext, error);
                }
            }

            @Override
            public void onSuccess(Object result) {
                DialogUtils.closeDialog();
                EntityBean bean = (EntityBean) result;
                if (bean != null) {
                    String restate = bean.getString("restate");
                    if (TextUtils.equals("1", restate)) {
                        EntityBean dataBean = bean.getBean("data");
                        if (null != dataBean) {
                            showInsDialog(dataBean);
                        }
                    }
                }
            }
        });
    }

    //显示进入理赔的提示框
    private void showInsDialog(final EntityBean dataBean) {
        final Dialog insDialog = new Dialog(mContext, R.style.AlertDialogStyle);
        View mView = View.inflate(mContext, R.layout.dialog_kckp, null);
        TextView insTV = (TextView) mView.findViewById(R.id.dialog_tv_ins);
        String text = mContext.getResources().getString(R.string.kckp_info);
        int color = mContext.getResources().getColor(R.color.lightyellow);
        insTV.setText(CommontUtils.changeStrColor(text, "15", color));
        mView.findViewById(R.id.dialog_btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String appno = dataBean.getString("appcaseno");
                String caseType = dataBean.getString("reporttype");
                EntityBean[] caseBeans = dataBean.getBeans("casecarlist");
                if (null != caseBeans) {
                    String isSingle = null;
                    if (caseBeans.length == 1) {//单车
                        isSingle = "0";
                    }
                    if (TextUtils.equals(caseType, "0")) {//未保险报案
                        InsuranceReportView view = new InsuranceReportView(mContext, caseBeans, appno, isSingle);
                        view.setFlag(0);
                        FrameworkManager.getInstance().showNewForm(mContext, view);
                    } else if (TextUtils.equals(caseType, "1")) {//未定损上传
                        NewLossLoadPicView lView = new NewLossLoadPicView(mContext, appno, 0);
                        lView.setCaseType(isSingle);
                        FrameworkManager.getInstance().showNewForm(mContext, lView);
                    }
                    PrefUtils.setBoolean(mContext, MsgConstant.HISTORY_CASE, false);
                }
                insDialog.dismiss();
            }
        });
        mView.findViewById(R.id.dialog_iv_delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean flag = PrefUtils.getBoolean(mContext, "insFirst", false);
                if (!flag) {
                    showInsGuidePop();
                    PrefUtils.setBoolean(mContext, "insFirst", true);
                }
                insDialog.dismiss();
            }
        });
        insDialog.setContentView(mView);
        insDialog.setCanceledOnTouchOutside(false);
        insDialog.setCancelable(false);
        insDialog.show();
    }

    private void showInsGuidePop() {
        final LinearLayout layout = new LinearLayout(mContext);
        layout.setOrientation(LinearLayout.VERTICAL);
        popupWindow = new PopupWindow(layout, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT, true);
        popupWindow.setBackgroundDrawable(new PaintDrawable());
        popupWindow.setFocusable(true);
        View parent = ((Activity) mContext).getWindow().getDecorView();
        popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);

        ImageView fView = new ImageView(mContext);
        fView.setScaleType(ImageView.ScaleType.FIT_XY);
        fView.setImageBitmap(CommontUtils.readBitmap(mContext, R.mipmap.popwindow_bg_3));
        fView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != popupWindow) {
                    popupWindow.dismiss();
                    popupWindow = null;
                }
            }
        });
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        layout.addView(fView, params);
        params = null;
        popupWindow.update();
    }

    @Override
    public Object onLSMsg(int arg0, Object... objects) {
        if (arg0 == 99) {//重新获取绑定的数据
            getBindData(false);
        } else if (arg0 == MsgConstant.PERMISSION) {
            if (objects != null && objects.length > 0 && "PERMISSION_GRANTED".equals(objects[0])) {
                startService();
                return false;
            }
        }
        return null;
    }

    @Override
    public Object onLFMsg(int i, Object... objects) {
        if (i == -10) {
            exit();
            return false;
        }
        return null;
    }

    private void startService() {
        BaseApplication application = ((MainActivity) mContext).getAppData();
        Intent intent = new Intent(mContext, LocationService.class);
        Bundle bundel = new Bundle();
        bundel.putString("method", URLConstant.GET_LOCATION);
        bundel.putString("uid", application.getKckpName());
        bundel.putString("token", application.getToken());
        bundel.putString("baseurl", mContext.getResources().getString(R.string.kckpServerUrl));
        intent.putExtra(LocationService.LOCATION, bundel);
        mContext.startService(intent);
    }

    private void exit() {
        if (!this.isExit) {
            this.isExit = true;
            Toast.makeText(mContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            this.mHandler.sendEmptyMessageDelayed(0, 2000L);
        } else {
            ((MainActivity) mContext).finish();
        }
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    @Override
    public void OnDestroy() {
        super.OnDestroy();
        setListen(false);
        removeILFMsgListener(this);
        removeILSMsgListener(this);
        if (null != kckpView) {
            kckpView.OnDestroy();
            kckpView = null;
        }
        if (null != myView) {
            myView.OnDestroy();
            myView = null;
        }
        if (null != carDailyView) {
            carDailyView.OnDestroy();
            carDailyView = null;
        }
        isBack = false;
        if (null != bodyLayout) {
            bodyLayout.removeAllViews();
            bodyLayout = null;
        }
        if (null != popupWindow) {
            popupWindow = null;
        }
        radioGroup = null;
        mView = null;
        mHandler = null;
        curShowView = null;
    }
}
